package com.zhouyu.exampleboot.controller;

import com.zhouyu.exampleboot.service.PoiService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;

@Controller
@RequestMapping("/file")
public class PoiController {
    
    @Autowired
    PoiService poiService;

    @RequestMapping("/test")
    public  void exPort(HttpServletRequest request,HttpServletResponse response){
        poiService.exporExcelFromBroser(request,response);
    }

    @GetMapping("/testCsvWrite")
    public void writeCsv() throws IOException {
        File file = new File("E:/");
        if (!file.exists()) {
            file.mkdirs();
        }

        String[] header={"工号","姓名","手机号码","证件类型","证件号码（身份证）","部门","职位","身份类型","性别"};
        //指定GBK,解决Microsoft不兼容
        Appendable printWriter = new PrintWriter(file + "/CSV-TEST.CSV","GBK");
        CSVPrinter csvPrinter = CSVFormat.DEFAULT.withHeader(header).print(printWriter);
        for (int i = 0; i < 10; i++) {
            csvPrinter.printRecord("10002" + i, "周宇" + i, 1202002028 + i,"1","42067712234234233",
                                   "研发部","研发工程师","2","男");
        }
        csvPrinter.flush();
        csvPrinter.close();
    }

    @PostMapping("/testCsv")
    public void readCsv(@RequestParam("file") MultipartFile file) throws IOException {
        Reader reader = new InputStreamReader(file.getInputStream(),"GBK");
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
        for (CSVRecord csvRecord : records) {
            // 第一行不会被打印出来
            long recordNumber = csvRecord.getRecordNumber();
            int size = csvRecord.size();
            String s0 =csvRecord.get(0);
            String s1 = csvRecord.get(1);
            String s2 =csvRecord.get(2);
            String s3 =csvRecord.get(3);
            String s4 =csvRecord.get(4);
            String s5 =csvRecord.get(5);
            String s6 =csvRecord.get(6);
            String s7 =csvRecord.get(7);
            String s8 =csvRecord.get(8);
            System.out.println(s1+","+s2+","+s3);
        }
        reader.close();
    }


}
